<script setup lang="ts">
import {PlayStatus, useAudioPlayerStore} from "@/stores"
import {onMounted, ref, watch} from "vue"

const audioPlayer = useAudioPlayerStore()
const canvasRef = ref<HTMLCanvasElement | null>(null)
const ctx = ref<CanvasRenderingContext2D | null>(null)
const bufferLength = audioPlayer.analyser.frequencyBinCount
const dataArray = new Uint8Array(bufferLength)
let CanvasAnimationFrameId:number = 0

onMounted(()=>{
  if(canvasRef.value !== null)
  {
    canvasRef.value.width = screen.width * devicePixelRatio
    ctx.value = canvasRef.value.getContext('2d')
    if(ctx.value !== null)
    {
      ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height)
      if(audioPlayer.status === PlayStatus.playing)
      {
        draw()
      }
    }
  }

})


watch(()=>audioPlayer.status,async (newValue)=>{
  if(newValue === PlayStatus.playing)
  {
    console.log("playing")
    draw()
  }
  else if(newValue === PlayStatus.pause)
  {
    console.log("取消动画")
    setTimeout(()=>{
      const playid = CanvasAnimationFrameId
      console.log("cancel",CanvasAnimationFrameId)
      cancelAnimationFrame(playid);
    },1000)

  }
  else
  {
    cancelAnimationFrame(CanvasAnimationFrameId);
  }

})

function draw() {

  if(canvasRef.value !== null && ctx.value !== null)
  {
    const width = canvasRef.value.width
    const height = canvasRef.value.height
    audioPlayer.analyser.getByteFrequencyData(dataArray);
    ctx.value.clearRect(0, 0, width, height);

    const gradient = ctx.value.createLinearGradient(0,height,0,0)
    gradient.addColorStop(0,'green')
    gradient.addColorStop(0.2,'yellow')
    gradient.addColorStop(0.6,'orange')
    gradient.addColorStop(1,'red')

    ctx.value.fillStyle = gradient

    //const barWidth = (canvas.width / bufferLength) * 2.5;
    //const barWidth = (width / bufferLength);
    const barWidth = 1
    const count = width  / barWidth
    let barHeight = 0;
    let x = 0;

    //ctx.value.fillStyle = 'rgba(0,255,128,0.8)'

    for (let i = 0; i < bufferLength && i < count ; i++) {
      const data = dataArray[i]
      barHeight = data / 255 * height;
      const x1 = i*barWidth + width / 2
      const x2 = width/2 - (i+1)*barWidth
      const y = height - barHeight

      //ctx.fillRect(i*2, canvas.height - barHeight, barWidth, barHeight);
      ctx.value.fillRect(x1, y, barWidth  , barHeight);
      ctx.value.fillRect(x2, y, barWidth  , barHeight);
      //x += barWidth + 1;
    }
  }

  CanvasAnimationFrameId = requestAnimationFrame(draw);
}



</script>

<template>
  <canvas id="player_canvas" ref="canvasRef"></canvas>
</template>

<style scoped lang="scss">
canvas{

  display: block;
  height: 75px;
  width: 100%;
  z-index: 1000;
  margin: 0 auto;
}
</style>